package com.sinog.biz.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @desc Base64工具类
 * @author lzq
 * @date 2020-11-16 9:21 上午
 */
@Slf4j
public final class Base64Util {

    /**
     * 描述
     * @param imgPath imgPath
     * @return String
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        InputStream in = null;
        // 读取图片字节数组
        try {
            in = Files.newInputStream(Paths.get(imgPath));
            log.info("文件大小（字节）={}",in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch(IOException e) {
            log.error("发生异常:{}",e.getMessage());
        } finally {
            if(null != in) {
                try {
                    in.close();
                } catch(IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 描述
     * @param fileBase64String fileBase64String
     * @param filePath filePath
     * @param fileName fileName
     */
    public static void convertBase64ToFile(String fileBase64String,String filePath,String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file;
        try {
            File dir = new File(filePath);
            //判断文件目录是否存在
            if(!dir.exists()) {
                dir.mkdirs();
            }
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch(IOException e) {
            log.error("发生异常:{}",e.getMessage());
        } finally {
            if(null != bos) {
                try {
                    bos.close();
                } catch(IOException e1) {
                    log.error("发生异常:",e1);
                }
            }
            if(null != fos) {
                try {
                    fos.close();
                } catch(IOException e1) {
                    log.error("发生异常:",e1);
                }
            }
        }
    }
}